var input = document.getElementById("input");
var output = document.getElementById("output");
var renderBtn = document.getElementById("render");
var demo = document.getElementById("demo");

var graphCode = input.value;
var editor = CodeMirror.fromTextArea(input, {
	mode: "simplemode",
	lineNumbers: true,
	matchBrackets: true,
	styleActiveLine: true,
	lineWrapping: true
});
//输入框聚焦
editor.focus();

editor.on('change', (editor, changes) => {
	graphCode = editor.getValue();
	
	if(autoRender.checked){
		clickRender();
	}
	// this.jsonFormattedSource = editor.getValue().replace(/\n/gm, ' ');
	// this.fireChange && this.format();
});

function clickRender(){
	let clickEvent = document.createEvent("MouseEvents");	  
	clickEvent.initEvent('click', true, true)
  
	render.dispatchEvent(clickEvent);
}

window.onerror = function(msg, url, line){
	var reg = /(?<=error on line )\d+(?=.)/
	var err = reg.exec(msg)
	if(err!=null && err[0] > 0){
		var line = err[0] - 1;
		editor.getDoc().markText(
			{line: line, ch: 1}, {line: line,ch: 100},
			{css: "text-decoration: underline wavy red"});

		editor.getDoc().markClean = function(){
			editor.getDoc().markText({line: line, ch: 1}, {line: line,ch: 100},{css: "text-decoration: white;"});
		}
	}
	return true;
}

var mermaidAPI = mermaid.mermaidAPI;
mermaidAPI.initialize({'securityLevel': 'loose', startOnLoad: false, useMaxWidth: true});


render.onclick = function() {
	editor.getDoc().markClean()
    mermaidAPI.render('myGraph', graphCode, function(svgCode) {
		output.innerHTML = svgCode;
		getDownloadUrl()
    });
}


function downloadSvg(){
	var url = getDownloadUrl();
	downImg(url);
}
function getDownloadUrl(){
	var svgXml = output.innerHTML;

	var image = new Image();
	image.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgXml))); //给图片对象写入base64编码的svg流

	var canvas = document.createElement('canvas');  //准备空画布
	var myGraph = document.getElementById("myGraph");

	canvas.width = myGraph.width.baseVal.value + 150;
	canvas.height = myGraph.height.baseVal.value;

	var context = canvas.getContext('2d');  //取得画布的2d绘图上下文
	context.drawImage(image, 0, 0);
	var url = canvas.toDataURL('image/png');
	return url;
}

function downImg(url) {
	let a = document.createElement("a")
	let clickEvent = document.createEvent("MouseEvents");
	a.setAttribute("href", url)
	a.setAttribute("download", 'codeGraph')
	a.setAttribute("target", '_blank')
	clickEvent.initEvent('click', true, true)
	a.dispatchEvent(clickEvent);
  
}

var demoList = [
	{"name":"sequence","mark":"时序图","code":"sequenceDiagram\n    participant 小程序\n    participant 开发者服务\n    participant 微信服务\n    小程序->>小程序: wx.login()获取code\n    小程序->>开发者服务: 发送code\n    开发者服务->>微信服务: code2session校验\n    微信服务->>开发者服务:  返回openid等\n    开发者服务->>开发者服务: 保存openid登录态\n    开发者服务->>小程序: 返回登录态标识\n    小程序->>开发者服务: 携带登录标识操作业务"},
	{"name":"flowchart","mark":"流程图","code":"flowchart LR\n    Demo1:\n   a --> b[[b]] & c([c])--> d[(Database)]\n   Demo2:\n    A o--o B\n    B <--> C\n    C x--x D"},
	{"name":"pie","mark":"饼图","code":'pie\n    title 产品X中元素比例\n    "盖" : 42.96\n    "钾" : 50.05\n    "镁" : 10.01\n    "铁" :  5'},
	{"name":"gantt","mark":"甘特图","code":"gantt\n   项目一 :a, 2017-07-20, 1w\n   项目二: crit, b, 2017-07-23, 1d\n   项目三 :active, c, after b a, 1d"},
	{"name":"class","mark":"类图","code":"classDiagram\nClass01 <|-- AveryLongClass : Cool\nClass03 *-- Class04\nClass05 o-- Class06\nClass07 .. Class08\nClass09 --> C2 : Where am i?\nClass09 --* C3\nClass09 --|> Class07\nClass07 : equals()\nClass07 : Object[] elementData\nClass01 : size()\nClass01 : int chimp\nClass01 : int gorilla\nClass08 <--> C2: Cool label"},
	{"name":"git","mark":"分支图","code":'gitGraph:\noptions\n{\n    "nodeSpacing": 150,\n    "nodeRadius": 10\n}\nend\ncommit\nbranch newbranch\ncheckout newbranch\ncommit\ncheckout master\ncommit\nmerge newbranch'},
	{"name":"er","mark":"实体关系图","code":"erDiagram\n    CUSTOMER ||--o{ ORDER : places\n    ORDER ||--|{ LINE-ITEM : contains\n    CUSTOMER }|..|{ DELIVERY-ADDRESS : uses"}
]
demoList.forEach(dem => {
	demo.options.add(new Option(dem.name+"("+dem.mark+")", dem.code))
});



var darkTheme = false

clickRender()

function hasClass( elements,cName ){ 
	return !!elements.className.match( new RegExp( "(\\s|^)" + cName + "(\\s|$)") ); 
  }; 
  function addClass( elementss,cName ){
	for (var index = 0; index < elementss.length; index++) {
		var elements = elementss[index];
		if( !hasClass( elements,cName ) ){ 
			elements.className += " " + cName; 
		  }; 
	}
  }; 
  function removeClass( elementss,cName ){ 
	for (var index = 0; index < elementss.length; index++) {
		var elements = elementss[index];
		if( hasClass( elements,cName ) ){ 
		elements.className = elements.className.replace( new RegExp( "(\\s|^)" + cName + "(\\s|$)" ), " " );
		};
	}
  };


var input2 = document.getElementById("select");
var themeVar = document.getElementsByClassName("ht");
var btns = document.getElementsByClassName("btn");
var darkTxt = "%%{init: {'theme': 'base', 'themeVariables': {'darkMode':true,'background':'#0C1021','primaryColor':'#F8F8F8','primaryTextColor':'#ddd','mainBkg':'#0C1021'}}}%%"

function selectTheme() {
  var theme = input2.options[input2.selectedIndex];
  if(theme.value != 'default'){
	darkTheme = true
	addClass(themeVar,"bg-dark")
	addClass(themeVar,"ht-dark")
	addClass(btns,"ht-dark")
	editorTxt(true)
  }else{
	darkTheme = false
	removeClass(themeVar,"bg-dark")
	removeClass(themeVar,"ht-dark")
	removeClass(btns,"ht-dark")
	editorTxt(false)
  }
  editor.setOption("theme", theme.value);
}

function editorTxt(dark){
	var txt = editor.getValue()
	var txtArr = txt.split("\n")
	for (var index = 0; index < txtArr.length; index++) {
		var tx = txtArr[index].trim()
		if(tx != ''){
			var noDarkTxt = (tx.indexOf("%%") == -1)
			if(noDarkTxt && dark){
				txt = darkTxt + "\n" + txt
				editor.setValue(txt)
				clickRender()
			}
			if(!noDarkTxt && !dark){
				txt = txt.replace(txtArr[index]+"\n","")
				editor.setValue(txt)
				clickRender()
			}
			break
		}
		
	}
}

function setDemo(){
	var val = demo.options[demo.selectedIndex].value;
	if(val.length > 3){
		if(darkTheme){
			val = darkTxt + "\n" + val
		}
		editor.setValue(val);
		clickRender();
		getDownloadUrl()
	}

}